<template>
	<el-breadcrumb class="app-breadcrumb" separator="/">
		<transition-group name="breadcrumb">
			<el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
				<span
					v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
					class="no-redirect"
					>{{ translateRouteTitle(item.meta.title) }}</span
				>
				<a v-else @click.prevent="handleLink(item)">{{
					translateRouteTitle(item.meta.title)
				}}</a>
			</el-breadcrumb-item>
		</transition-group>
	</el-breadcrumb>
</template>

<script setup lang="ts">
import { RouteLocationMatched, RouteLocationRaw } from "vue-router";
import { compile } from "path-to-regexp";
import { translateRouteTitle } from "@/utils/i18n";
const levelList = ref([] as Array<RouteLocationMatched>);

const route = useRoute();
const router = useRouter();
/**
 * @description: 获取面包屑
 */
const getBreadcrumb = () => {
	// only show routes with meta.title
	let matched = route.matched.filter((item) => item.meta && item.meta.title);

	levelList.value = matched.filter(
		(item) => item.meta && item.meta.title && item.meta.breadcrumb !== false
	);
};

watch(
	() => route.path,
	(path) => {
		if (path.startsWith("/redirect/")) {
			return;
		}
		getBreadcrumb();
	}
);
onBeforeMount(() => {
	getBreadcrumb();
});
/**
 * @description: 点击跳转
 * @param {*} item
 */
const handleLink = (item: RouteLocationMatched) => {
	const { redirect, path } = item;
	if (redirect) {
		router.push(redirect as RouteLocationRaw);
		return;
	}
	router.push(pathCompile(path));
};
/**
 * @description: pathCompile
 * @param {*} path
 * @return {*}
 */
const pathCompile = (path: string) => {
	const { params } = route;
	const toPath = compile(path);
	return toPath(params);
};
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
	display: inline-block;
	font-size: 14px;
	line-height: 50px;
	margin-left: 8px;

	.no-redirect {
		color: var(--el-color-primary);
		cursor: text;
	}
}
</style>
